#-------------------------------------------------------------------------------
#
# Electoral predictors - average expected edb last poll margin results
#
# Author: Sina Chen
#
#-------------------------------------------------------------------------------


# Libraries ---------------------------------------------------------------

{
  library(rv)
  library(gtools)
  library(rstan)
  library(dplyr)
  library(scales)
}

setnsims(10000)


# Data --------------------------------------------------------------------

# polls
polls <- readRDS("data/us_senate_polls1990_2022_final.RDS")

# simulation results
resStan <- readRDS('code/fit_stan/resStan_us_senate_context1990_2022_last.RDS')


# Functions ---------------------------------------------------------------

# extra rv functins
ilogit.rv <- function(x) rvmapply(FUN = inv.logit, x) # taken from Bon et al. (2019)
logit.rv <- function(x) rvmapply(FUN = logit, x) # taken from Bon et al. (2019)


# Preparation -------------------------------------------------------------

polls <- polls %>%
  filter(dte < 101) %>% 
  group_by(state, cycle) %>% 
  mutate(n_poll = n(),
         last_poll = max(end_date)) %>% 
  ungroup() %>% 
  filter(n_poll >= 5) %>% 
  mutate(state_year = paste0(state, cycle),
         cycle = as.integer(cycle),
         state_year_int = as.integer(as.factor(state_year)),
         t_sc = as.numeric(dte)/max(as.numeric(dte)),
         last_poll_margin = if_else(end_date == last_poll, pct2_rep-pct2_dem, 
                                    NA_real_))

# election-level data 
election_data <- polls %>%
  group_by(state_year, state_year_int, cycle,  state, vote2_rep) %>%
  summarise(last_poll_margin = mean(last_poll_margin, na.rm = T)) %>%
  ungroup()

# convert simulations to random variable (rv) obj.
postrv <- as.rv(resStan)


# Average expected EDB ----------------------------------------------------

avg_b0_last <- rv(length = length( election_data$last_poll_margin))

for(i in 1:nrow(election_data)){
  b0_sim_r_i <- sapply(election_data$vote2_rep, 
                       function(x) 
                         ilogit.rv(logit.rv(x) +
                                     postrv$mu_alpha + 
                                     postrv$beta2*election_data$last_poll_margin[i]) - 
                         x)
  avg_b0_last[[i]] <- colMeans(do.call(rbind,b0_sim_r_i))
  print(i)
  
}

# summary
avg_b0_last_summary <- summary(avg_b0_last)
avg_b0_last_summary$state_year_int <- 1:nrow(election_data)
avg_b0_last_summary <- merge(avg_b0_last_summary, election_data, by = "state_year_int")

# save
saveRDS(avg_b0_last_summary, "code/results_vis/us_senate_avg_exp_b0_last.RDS")


